package com.qiangzhi.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置类 用于配置Redis缓存有效时间
 */
@Configuration
@Slf4j
public class RedisConfiguration extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofDays(1)); // 设置默认缓存 缓存有效时间为1天
        log.info("设置redis缓存默认有效时间为：{}天", cacheConfiguration.getTtl().toDays());
        // 针对不同cacheName 设置不同的有效时间，map的key是缓存名称
        Map<String, RedisCacheConfiguration> initialCacheConfiguration = new HashMap<>(8);
        // allCollegeCache 设定有效时间为1小时
        initialCacheConfiguration.put("allCollegeCache", getDefaultSimpleConfiguration().entryTtl(Duration.ofHours(1)));
        // majorCache 设定有效时间为30分钟
        initialCacheConfiguration.put("majorCache", getDefaultSimpleConfiguration().entryTtl(Duration.ofMinutes(30)));
        return RedisCacheManager
                .builder(redisConnectionFactory)
                // 设置缓存默认有效时间配置
                .cacheDefaults(cacheConfiguration)
                // 设置不同cacheName的个性化配置
                .withInitialCacheConfigurations(initialCacheConfiguration).build();
    }

    /**
     * 覆盖默认的构造key 默认拼接的时候是两个冒号（::） 否则会多出一个冒号
     *
     * @return 返回缓存配置信息
     */
    private RedisCacheConfiguration getDefaultSimpleConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig().computePrefixWith(cacheName -> cacheName + ":");
    }

}
